package org.millioncall.yueyoga.admin.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.millioncall.openplatform.common.PaginatedList;
import org.millioncall.openplatform.util.WebAppUtils;
import org.millioncall.yueyoga.admin.model.AviatorExpression;
import org.millioncall.yueyoga.admin.model.GoodType;
import org.millioncall.yueyoga.admin.model.Goods;
import org.millioncall.yueyoga.admin.model.Group;
import org.millioncall.yueyoga.admin.model.GroupUserModel;
import org.millioncall.yueyoga.admin.model.Member;
import org.millioncall.yueyoga.admin.model.User;
import org.millioncall.yueyoga.admin.service.GoodTypeService;
import org.millioncall.yueyoga.admin.service.GoodsService;
import org.millioncall.yueyoga.admin.service.MemberService;
import org.millioncall.yueyoga.admin.service.UserService;
import org.millioncall.yueyoga.common.GlobalConstants;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * @author lisj Mar 27, 2014 2:50:21 PM
 */
@Controller
public class GoodsAction extends BaseAction {

	private GoodsService goodservive;
	private GoodTypeService goodTypeService;
	private UserService userService;
	private MemberService memberService;
	private static final String GOODS_SEARCH = "goods_search"; // 商品列表
	
	/** 高级搜索商品 */
	@RequestMapping(value = "/ajaxAdvSearchGoods.jhtml")
	public void advSearchMember(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String strLimit = request.getParameter("limit");

		String exp = request.getParameter("expression");
		String expType = request.getParameter("expType");

		String msg = "";

		int limit = Integer.MAX_VALUE;

		try {
			limit = Integer.parseInt(strLimit);
		} catch (NumberFormatException e) {
			limit = Integer.MAX_VALUE;
		}

		if (StringUtils.isBlank(exp)) {
			msg = "{'success':false, 'msg':'表达式不能为空！'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		if (StringUtils.isBlank(expType)) {
			msg = "{'success':false, 'msg':'表达式类型不能为空！'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		// 用于过滤会员的条件map
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("hallcode", this.getUser(request).getOrganizationId());

		// 条件表达式
		// 在此组装条件表达式
		AviatorExpression expression = new AviatorExpression();
		expression.setExpression(exp);
		// 条件表达式的map
		Map<String, Object> aviatorParams = new HashMap<String, Object>();
		aviatorParams.put(GlobalConstants.RESULT_ROW_MODEL_KEY, expType);

		List<Goods> goods = this.goodservive.getAllGoodsWithAviator(params, expression, aviatorParams, limit);

		if (goods.size() > 0) {
			String json = JSON.toJSONStringWithDateFormat(goods, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat);
			msg = "{'success':true, 'total':'" + goods.size() + "', 'items':"
					+ json + "}";
		} else {
			msg = "{'success':true, 'total':'0', 'items':''}";
		}

		WebAppUtils.ajaxResponse(response, msg);
	}

	@RequestMapping(value = "/toAddGoods.jhtml")
	public String toAddGoods(HttpServletRequest request, ModelMap model) {
		super.initFrontHeader(request, model);
		List<GoodType> goodTypes= goodTypeService.findAll();
		model.put("types", goodTypes);
		return "goods_add";
	}
	
	@RequestMapping(value = "/toEditGoods.jhtml")
	public String toEditGoods(String goodsId,HttpServletRequest request, ModelMap model) {
		super.initFrontHeader(request, model);
		Goods goods = new Goods();
		if(StringUtils.isNotBlank(goodsId)){
			goods = goodservive.findGoodsById(Integer.valueOf(goodsId));
		}
		
		List<GoodType> goodTypes= goodTypeService.findAll();
		model.put("types", goodTypes);
		model.put("goods", goods);
		return "goods_edit";
	}

	@RequestMapping(value = "/updateGoods.jhtml")
	public String updateGoods(HttpServletRequest request, Goods goods,
			ModelMap map) {
		super.initFrontHeader(request, map);
		if (goods != null) {
			if (goods.getId() != null) {
				// --修改商品信息 update goods successs
				if (goodservive.update(goods)) {
					// --修改成功
					map.put("msg", "ugs");
				} else {
					map.put("msg", "ugf");
					return "goods_edit";
				}
			} else {
				// --添加商品信息
				// --添加成功：save goods success
				// --添加失败：save goods fail
				User user = this.getUser(request);
				goods.setOrganizationId(user.getOrganizationId());
				if (goodservive.save(goods)) {
					// --添加成功
					map.put("msg", "sgs");
				} else {
					map.put("msg", "sgf");
					return "goods_add";
				}
			}
		}
		return "redirect:searchGoods.jhtml";
	}

	// 查询商品信息
	@RequestMapping(value = "/searchGoods.jhtml")
	public String findGoodsByConditions(String goodsCode, String goodsName,
			String goodsType, String goodsStatus, String pageNo,
			String pageSize, HttpServletRequest request, ModelMap model) {
		super.initFrontHeader(request, model);
		User user = this.getUser(request);
		int start = 0;
		int limit = 10;
		Map<String, Object> map = new HashMap<String, Object>();
		
		String display = request.getParameter("display");
		if("block".equals(display)){
			model.put("display",display);
		}
		
		if (StringUtils.isNotBlank(pageSize)) {
			limit = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNotBlank(pageNo)) {
			start = (Integer.parseInt(pageNo) - 1) * limit;
		}
		if (StringUtils.isNotBlank(goodsCode)) {
			map.put("code", goodsCode);
			model.put("code", goodsCode);
		}
		if (StringUtils.isNotBlank(goodsName)) {
			map.put("name", goodsName);
			model.put("name", goodsName);
		}
		if (StringUtils.isNotBlank(goodsType)) {
			map.put("type", goodsType);
			model.put("type", goodsType);
		}
		if (StringUtils.isNotBlank(goodsStatus)) {
			map.put("status", goodsStatus);
			model.put("status", goodsStatus);
		}

		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		PaginatedList<Goods> goods = null;
		if("block".equals(display)){
			 goods = goodservive.findGoodsInPage(map, start,
					limit);
		}
		model.put("goods", goods);
		// 查询商品类型
		List<GoodType> goodTypes= goodTypeService.findAll();
		model.put("types", goodTypes);
		// 查询卖出人
		List<GroupUserModel> respors = this.userService.findUsersByGroupId("4",
				user.getOrganizationId());
		model.put("respors", respors);
		// 查询会员
		
		Map<String, Object> map1 = new HashMap<String, Object>();
		map1.put("key", "organizationId");
		map1.put("value", user.getOrganizationId());
		map1.put("groups", groupIds);
		map1.put("hallcode",this.getUser(request).getOrganizationId());
		List<Member> members = memberService.findMemberByProperty(map1);
		model.put("members", members);

		return GOODS_SEARCH;
	}

	// 指定库存数量
	@RequestMapping(value = "/saveGoodsCounts.jhtml")
	public String findGoodsCounts(ModelMap context, HttpServletRequest request) {
		super.initFrontHeader(request, context);
		Map<String, Object> map = new HashMap<String, Object>();
		String strOldCounts = request.getParameter("oldCounts");
		String strCounts = request.getParameter("counts");
		String strGoodId = request.getParameter("goodId");
		int oldCounts = 0;
		int counts = 0;
		int sum = 0;
		if (StringUtils.isNotBlank(strGoodId)) {
			int goodId = Integer.parseInt(strGoodId);
			map.put("goodId", goodId);
		}
		if (StringUtils.isNotBlank(strOldCounts)
				&& StringUtils.isNotBlank(strCounts)) {
			oldCounts = Integer.parseInt(strOldCounts);
			counts = Integer.parseInt(strCounts);
			sum = oldCounts + counts;
			map.put("sum", sum);
		}
		boolean b = goodservive.updateGoodCounts(map);
		if (b) {
			context.put("msg", "success");
		} else {
			context.put("msg", "failure");
		}
		return "goods_search";
	}

	// 根据商品id集合删除商品信息
	@RequestMapping(value = "/deleteGoodsByIds.jhtml")
	public void deleteGoodsByIds(String chkIds, HttpServletRequest request,
			HttpServletResponse response) {
		String msg = "";
		if (StringUtils.isBlank(chkIds)) {
			msg = "false";
		} else {
			String[] ids = chkIds.split(",");
			if (goodservive.deleteByIds(ids)) {
				msg = "true";
			} else {
				msg = "false";
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	public GoodsService getGoodservive() {
		return goodservive;
	}

	public void setGoodservive(GoodsService goodservive) {
		this.goodservive = goodservive;
	}

	public GoodTypeService getGoodTypeService() {
		return goodTypeService;
	}

	public void setGoodTypeService(GoodTypeService goodTypeService) {
		this.goodTypeService = goodTypeService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}
	
}
